<script setup>
//实现原生 table 实现列表展示,有添加、删除、修改、查看功能,并且使用localStorage 进行数据持久化
import { reactive, ref, computed, watch } from "vue"
const arr = reactive(JSON.parse(localStorage.getItem("arr") || "[]"))
const selected = ref(-1) // -1 添加 0-n 修改
const form = reactive({
  title: "",
  date: "",
})
const currentIndex = ref(0)

const displayArr = computed(() => {
  return arr.slice(currentIndex.value, currentIndex.value + 10)
})

watch(
  () => arr,
  () => {
    localStorage.setItem("arr", JSON.stringify(arr))
  },
  { deep: true }
)
// 为什么点击onsubmit之后没有渲染数据在页面?
// 因为你没有把数据添加到arr中
const onSubmit = () => {
  if (selected.value === -1) {
    // 添加
    // a:因为 id 是唯一的，如果不这样配置，那么就会出现 id 重复的情况
    arr.push({ ...form, id: Date.now() + Math.floor(Math.random() * 1000) })
  } else {
    // 修改
    arr[selected] = { ...arr[selected], ...form }
  }
  form.title = ""
  form.date = ""
}
const onEdit = (index) => {
  selected.value = index
  form.title = arr[index].title
  form.date = arr[index].date
}

const onDelete = (index) => {
  arr.splice(index, 1)
}
const onClear = () => {
  arr.splice(0, arr.length)
}
const onMock = () => {
  for (let i = 1; i <= 10; i++) {
    arr.push({
      title: i + "",
      date: "2020-01-01",
      id: i + "",
    })
  }
}

// 实现arr列表的拖拉拽排序
const onDragStart = (event, index) => {
  event.dataTransfer.setData("index", index)
}
const onDragOver = (event) => {
  event.preventDefault()
}
const onDrop = (event, index) => {
  const from = event.dataTransfer.getData("index")
  const temp = arr[from]
  arr.splice(from, 1)
  arr.splice(index, 0, temp)
}





</script>

<template>
  <div>
    <h1>CrudDome</h1>
    <div>
      <input type="text" v-model="form.title" />
      <input type="date" v-model="form.date" />
      <button @click="onSubmit">提交</button>
    </div>
    <div>
      <button @click="onMock">模拟数据</button>
      <button @click="onClear">清空数据</button>
    </div>
    <table>
      <thead>
        <tr>
          <th>标题</th>
          <th>日期</th>
          <th>操作</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="(item, index) in displayArr" :key="item.id">
          <td>{{ item.title }}</td>
          <td>{{ item.date }}</td>
          <td>
            <button @click="onEdit(index)">编辑</button>
            <button @click="onDelete(index)">删除</button>
          </td>
        </tr>
      </tbody>
    </table>
  </div>
</template>